package org.fatmansoft.teach.controllers.ViewController;

import org.fatmansoft.teach.Repository.ViewRepository.CourseRepository;
import org.fatmansoft.teach.Repository.ViewRepository.TeacherRepository;
import org.fatmansoft.teach.entity.ViewEntity.Course;
import org.fatmansoft.teach.entity.ViewEntity.Teacher;
import org.fatmansoft.teach.payload.request.DataRequest;
import org.fatmansoft.teach.payload.response.DataResponse;
import org.fatmansoft.teach.util.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/courseInfo")
public class CourseController {
    @Autowired
    CourseRepository courseRepository;

    @Autowired
    TeacherRepository teacherRepository;

    @PostMapping("/getInfo")
    public DataResponse getInfo(@Valid @RequestBody DataRequest request) {
        Map<String, Object> map = new HashMap<>();

        int currentPage = 1;  //分页页码
        String RequestCurPage = Utils.parseRequest(request, "currentPage", map);  //获取解析的数据
        if (RequestCurPage != null & Utils.checkNum(RequestCurPage)) {  //要求数据不为空，且为纯数字
            currentPage = Integer.parseInt(RequestCurPage);
        }

        String id = "";  //课序号
        String RequestCouNum = Utils.parseRequest(request, "id", map);  //获取解析的数据
        if (RequestCouNum != null) {  //要求数据不为空
            id = RequestCouNum;
        }

        List<Course> courseList = new ArrayList<>();  //创建课程列表，用于返回前端
        if (!id.equals("")) {  //按照课序号查询
            courseList = courseRepository.findCourseById(Integer.parseInt(id));
        } else {  //不按照课序号查询
            courseList = courseRepository.findAll(PageRequest.of(currentPage - 1, 5)).toList();
        }

        List<Teacher> teacherList = teacherRepository.findAll().subList(0, teacherRepository.findAll().size());
        map.put("tableData", courseList);
        map.put("teacherList", teacherList);
        map.put("total", courseRepository.findAll().size());

        return new DataResponse("0", map);
    }

    @PostMapping("/deleteInfo")
    public DataResponse delete(@Valid @RequestBody DataRequest request) {
        Map<String, Object> map = new HashMap<>();

        String deleteId = Utils.parseRequest(request, "deleteId", map);
        //System.out.println(deleteId);
        if (Utils.checkNum(deleteId)) {
            courseRepository.deleteById(Integer.parseInt(deleteId));
        }

        return new DataResponse("0", map);
    }

    @PostMapping("/updateAndCreateInfo")
    public DataResponse updateAndCreate(@Valid @RequestBody DataRequest request) throws ParseException {
        Map<String, Object> map = new HashMap<>();
        String code;

//        从前端获取formData转化为Map
        Map formData = (Map) request.getData().get("formData");
        Course course = new Course();


        if (formData.get("id") != null) course.setId(Integer.parseInt(formData.get("id").toString()));
        else {  //如果没有传入id->查找数据库，补全ID
            int lastRecord = courseRepository.findAll().size() - 1;
            int lastId = courseRepository.findAll().get(lastRecord).getId();
            course.setId(lastId + 1);
        }
        if (formData.get("courseName") != null)
            course.setCourseName(formData.get("courseName").toString());
        if (formData.get("book") != null)
            course.setBook(formData.get("book").toString());
        if (formData.get("courseInfo")!=null)
            course.setCourseInfo(formData.get("courseInfo").toString());
        if (formData.get("credit")!=null)
            course.setCredit(Integer.parseInt(formData.get("credit").toString()));
        if (formData.get("teacher") != null) {  //获取老师的方法
            Teacher teacher=new Teacher();
            if (teacherRepository.findById((int) Long.parseLong(formData.get("teacher").toString())).isPresent()) {
                teacher = teacherRepository.findById((int) Long.parseLong(formData.get("teacher").toString())).get();
            }
            course.setTeacher(teacher);
        }
//        判断当前元组是否已经存在（根据ID是否存在)
        if (courseRepository.findById(course.getId()).isPresent()) {  //查看id是否已经存在
            code = "0"; //表示更新
        } else {
            code = "1"; //表示新增
        }

        courseRepository.save(course);  //更新/保存的数据

        return new DataResponse(code, map);
    }

}
